package com.physics;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

import com.physics.bodies.Body;

import android.util.Log;

/**
 * User: cwatts
 * <p/>
 * Date: 12/30/11
 * <p/>
 * World is used to
 */
public class World
{
	private static final String TAG = World.class.getSimpleName();

	private final int MaxNumberOfBodies = 100;
	private List<Body> bodiesInUse;

	private Stack<Body> availableBodies;

	public World()
	{
		this.bodiesInUse = new ArrayList<Body>();
		this.availableBodies = new Stack<Body>();
	}

	/**
	 * Creates a body if there are no bodies in the available bodies list.
	 * @param bodyClass the type of body we want to create.
	 * @return the created body.
	 */
	public Body createBody(Class<Body> bodyClass)
	{
		Body body = null;

		if (this.availableBodies.empty())
		{
			try
			{
				body = bodyClass.newInstance();
			}
			catch (InstantiationException e)
			{
				Log.e(TAG, e.toString());
			}
			catch (IllegalAccessException e)
			{
				Log.e(TAG, e.toString());
			}
		}
		else
		{
			body = this.availableBodies.pop();
		}

		if (body == null)
		{
			Log.e(TAG, "Unable to create physics body.");
		}
		else
		{
			Log.d(TAG, "Physics body created");
		}

		return body;
	}

	/**
	 * Destroys a physics body from the world.
	 * @param body The body to destroy.
	 */
	public void destroyBody(Body body)
	{
		if (body == null)
		{
			Log.e(TAG, "Cannot pass null body to destroy.");
		}

		this.bodiesInUse.remove(body);

		Log.d(TAG, "Physics Body destroyed.");
	}
}
